package com.cheetah.start.module.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.solon.plugins.pagination.Page;
import com.cheetah.start.common.base.query.PageQuery;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTable;
import com.cheetah.start.common.enums.BusinessTypeEnum;
import com.cheetah.start.common.util.LoginSysUtil;
import com.cheetah.start.common.util.PasswordUtil;
import com.cheetah.start.module.system.domain.SysAdmin;
import com.cheetah.start.module.system.domain.SysDictData;
import com.cheetah.start.module.system.domain.SysRole;
import com.cheetah.start.module.system.service.SysAdminService;
import com.cheetah.start.module.system.service.SysDictDataService;
import com.cheetah.start.module.system.service.SysRoleAdminService;
import com.cheetah.start.module.system.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.validation.annotation.NotBlank;
import org.noear.solon.validation.annotation.NotNull;
import org.noear.solon.validation.annotation.Validated;

import java.util.List;

/**
 * @author Feel
 * @create 2021/7/18
 **/
@Slf4j
@Controller
@Mapping("/system/admin")
public class SysAdminController extends ResultController {

    @Inject
    SysAdminService sysAdminService;
    @Inject
    SysRoleService sysRoleService;
    @Inject
    SysDictDataService sysDictDataService;
    @Inject
    SysRoleAdminService sysRoleAdminService;

    /**
     * 列表页面
     *
     * @return {@link ModelAndView}
     */
    @Mapping("/data")
    @Get
    public ModelAndView list(ModelAndView modelAndView) {
        List<SysDictData> dictData = sysDictDataService.getByDictCode("sex");
        modelAndView.put("dictSex", dictData);
        modelAndView.view("/user/list.html");
        return modelAndView;
    }

    /**
     * 添加页面
     *
     * @param modelAndView 模型和视图
     * @return {@link ModelAndView}
     */
    @Mapping("/add")
    public ModelAndView addView(ModelAndView modelAndView) {
        List<SysRole> list = sysRoleService.listEnable();
        List<SysDictData> dictData = sysDictDataService.getByDictCode("sex");
        modelAndView.put("sysRoles", list);
        modelAndView.put("dictSex", dictData);
        modelAndView.view("/user/add.html");
        return modelAndView;
    }

    @Get
    @Mapping("/edit")
    public ModelAndView edit(ModelAndView modelAndView, Integer adminId) {
        List<SysDictData> dictData = sysDictDataService.getByDictCode("sex");
        modelAndView.put("dictSex", dictData);
        modelAndView.put("sysUser", sysAdminService.getById(adminId));
        modelAndView.put("sysRoles", sysRoleService.getAllRoleWithCheck(adminId));
        modelAndView.view("/user/edit.html");
        return modelAndView;
    }


    /**
     * 登录
     *
     * @param sysAdmin 系统管理员
     * @return {@link Result}
     */
    @Mapping("/login")
    @Post
    public Result login(SysAdmin sysAdmin) {
        SysAdmin one = sysAdminService.getByName(sysAdmin.getName());
        if (one != null && PasswordUtil.valid(sysAdmin.getPassword(), one.getPassword())) {
            LoginSysUtil loginSysUtil = LoginSysUtil.get();
            loginSysUtil.loginPc(one.getAdminId());
            loginSysUtil.setName(one.getName());
            return success("登录成功");
        }
        return failure("账号或密码错误");
    }

    /**
     * 改变
     *
     * @param oldpwd oldpwd
     * @param newpwd newpwd
     * @return {@link Result<?>}
     */
    @Mapping("/change")
    @Post
    public Result<?> change(@NotBlank(message = "旧密码不能为空") String oldpwd,
                            @NotBlank(message = "新密码不能为空") String newpwd) {
        SysAdmin admin = sysAdminService.getById(LoginSysUtil.get().getLoginId());
        if (PasswordUtil.valid(oldpwd, admin.getPassword())) {
            admin.hashPwd(newpwd);
            return decide(sysAdminService.updateById(admin), BusinessTypeEnum.EDIT);
        }
        return failure("密码错误");
    }

    /**
     * 注销
     *
     * @return {@link Result}
     */
    @Mapping("/logout")
    @Get
    public Result logout() {
        LoginSysUtil.get().logOut();
        return success("退出登录");
    }


    /**
     * 信息
     *
     * @return {@link Result}
     */
    @Get
    @Mapping("/info")
    @SaCheckLogin
    public Result info() {
        SysAdmin sysAdmin = sysAdminService.getById(LoginSysUtil.get().getLoginId());
        return success(sysAdmin);
    }

    /**
     * 列表
     *
     * @param pageQuery 页面查询
     * @param admin     管理
     * @return {@link ResultTable}
     */
    @Get
    @SaCheckPermission(value = "sys:admin:data", orRole = "admin")
    @Mapping("/list")
    public ResultTable list(PageQuery pageQuery, SysAdmin admin) {
        Page<SysAdmin> page = sysAdminService.pageList(pageQuery, admin);
        return pageTable(page.getRecords(), page.getTotal());
    }

    /**
     * 添加
     *
     * @param sysAdmin 系统管理员
     * @return {@link Result}
     */
    @SaCheckPermission(value = "sys:admin:add", orRole = "admin")
    @Mapping("/save")
    @Post
    public Result add(@Validated SysAdmin sysAdmin) {
        if (sysAdminService.isRepeat(sysAdmin)) {
            return failure("账户名不能重复");
        }
        sysAdmin.hashPwd();
        boolean save = sysAdminService.saveWithRoleIds(sysAdmin);
        return decide(save, BusinessTypeEnum.ADD);
    }

    /**
     * 更新
     *
     * @param sysAdmin 系统管理员
     * @return {@link Result}
     */
    @SaCheckPermission(value = "sys:admin:edit", orRole = "admin")
    @Mapping("/update")
    @Post
    public Result update(@Validated SysAdmin sysAdmin) {
        SysAdmin admin = sysAdminService.getById(sysAdmin.getAdminId());
        if ("admin".equals(admin.getName()) && !"admin".equals(sysAdmin.getName())) {
            return failure("不能修改超级管理员账户名");
        }
        if (sysAdminService.isRepeat(sysAdmin)) {
            return failure("账户名不能重复");
        }
        boolean b = sysAdminService.updateByIdWithRole(sysAdmin);
        return decide(b, BusinessTypeEnum.EDIT);
    }

    /**
     * 删除
     *
     * @param adminId 管理员id
     * @return {@link Result}
     */
    @SaCheckPermission(value = "sys:admin:delete", orRole = "admin")
    @Mapping("/delete")
    @Delete
    public Result delete(@NotNull(message = "ID不能为空") Integer adminId) {
        SysAdmin byId = sysAdminService.getById(adminId);
        if ("admin".equals(byId.getName())) {
            return failure("超级管理员不能删除");
        }
        boolean b = sysAdminService.removeById(adminId);
        sysRoleAdminService.removeByAdminId(adminId);
        return decide(b, BusinessTypeEnum.REMOVE);
    }

}
